<template>
  <div class="pad-20 bgc-default">
    <div class="pad-20 bg-color-white">
      <div>
        <el-button @click="handleCreate" type="primary">添加商品</el-button>
        <el-button @click="openImportGoods">批量导入商品</el-button>
        <el-button @click="handleCopyWholesale"
          v-if="(getVersionType() == 1 || getVersionType() == 4) && enterpriseConfig.wholesaleAuthority == 1">导入批发库商品
        </el-button>
        <el-upload style="display: inline-block; margin-left: 10px;" action="/api/goods/projectGoods/uploadTaoBaoZip"
          :before-upload="beforeZipUpload" name="files" v-loading="fileLoading" :data="uploadParams"
          :show-file-list="false" :on-success="handleUploadZipSuccess">
          <el-button>导入淘宝商品</el-button>
        </el-upload>
        <el-link type="primary" @click="openExternalCodeConfigDialog">外部编码规则生成设置</el-link>
      </div>
      <!--顶部搜索 -->
      <div class="top-operate-default  mar-t-20  flex-col" style="align-items: baseline; height: 100%; ">
        <div class="search-item mar-5">
          <label class="font-14">商品搜索：</label>
          <el-select class="select-class" v-model="textCol" style="width: 120px">
            <el-option label="商品名称" value="title"></el-option>
            <el-option label="商品货号" value="goodsCode"></el-option>
            <el-option label="商品条码" value="goodsBarCode"></el-option>
            <el-option label="外部编码" value="externalCode"></el-option>
            <el-option label="sku外部编码" value="skuExternalCode"></el-option>
          </el-select>
          <el-input @keyup.enter.native="handleSearch" v-model.trim="searchKeyword" placeholder="请输入关键词"
            style="width: 220px;"></el-input>
          <label class="font-14 mar-l-20">商品品牌：</label>
          <el-select class="select-class" v-model="brandId" style="width: 120px">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="item in listBrands" :key="item.brandId" :label="item.brandName" :value="item.brandId">
            </el-option>
          </el-select>
          <label class="font-14 mar-l-20">商品分类：</label>
          <el-cascader v-model="categoryIds" :props="{ checkStrictly: true }" change-on-select placeholder="选择商品分类"
            :options="categoryData" class="special-input" clearable></el-cascader>
          <label class="font-14 mar-l-20">商品来源：</label>
          <el-select v-model="supplierType" style="width: 120px">
            <el-option label="全部" value=""></el-option>
            <el-option label="总部自营" value="1"></el-option>
            <el-option label="供货联盟" value="3"></el-option>
            <el-option label="淘宝联盟" value="2"></el-option>
            <el-option v-for="(item, index) in supplierList" :key="index" :label="item.supplierName"
              :value="item.supplierId"></el-option>
          </el-select>
          <label class="font-14 mar-l-20">直播商品库：</label>
          <el-select v-if="getVersionType() == 1 || getVersionType() == 4" v-model="searchListQuery.liveGoodsType"
            style="width: 120px">
            <el-option label="全部" value=""></el-option>
            <el-option label="已加入" value="1"></el-option>
            <el-option label="未加入" value="0"></el-option>
          </el-select>
        </div>
        <div class="search-item mar-5">
          <label class="font-14" v-if="enterpriseConfig.anchorSelectionAuthority == '1'">主播选品库：</label>
          <el-select
            v-if="(getVersionType() == 1 || getVersionType() == 4) && enterpriseConfig.anchorSelectionAuthority == '1'"
            v-model="searchListQuery.selectionGoodsType" style="width: 120px">
            <el-option label="全部" value=" "></el-option>
            <el-option label="已加入" value="1"></el-option>
            <el-option label="未加入" value="0"></el-option>
          </el-select>
          <template v-if="enterpriseConfig.crossBorderBusinessFlag === 1">
            <label class="font-14 mar-l-20">跨境类型：</label>
            <el-select v-model="searchListQuery.crossBorderType">
              <el-option label="全部" value=""></el-option>
              <template v-for="(val, key) in dict.crossBorderType">
                <el-option :label="val" :key="key" :value="key"></el-option>
              </template>
            </el-select>
          </template>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button plain @click="resetSearch">重置</el-button>
          </el-button-group>
          <el-button class="mar-l-20" @click="handleExport">导出</el-button>
        </div>
      </div>
      <!--商品状态 -->
      <div class="tabs-box mar-t-20">
        <el-tabs type="card" v-model="pagingStatus" @tab-click="goodsStatusClick">
          <el-tab-pane label="全部" name="0"></el-tab-pane>
          <el-tab-pane label="上架中" name="1"></el-tab-pane>
<!--          <el-tab-pane label="已售空" name="2"></el-tab-pane>-->
          <el-tab-pane label="仓库中" name="3"></el-tab-pane>
        </el-tabs>
      </div>
      <div>
        <div class="pad-t-15 pad-b-15 font-14 v-align-c">
          <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span
              class="mar-l-20">当页全选</span></el-checkbox>
          <span class="pad-l-4 pad-r-4">|</span>
          <div class="width-80">已选{{multipleSelection.length}}项</div>
          <el-button class="batch-btn" @click="handleBatchDown" v-if="pagingStatus === '0' || pagingStatus === '1'">批量下架
          </el-button>
          <el-button class="batch-btn" @click="openBatchSelectionGoodsDialog"
            v-if="enterpriseConfig.anchorSelectionAuthority == '1' && (pagingStatus === '0' || pagingStatus === '1')">
            批量加入/移出选品库</el-button>
          <el-button class="batch-btn" @click="handleBatchDelete" v-if="pagingStatus === '2' || pagingStatus === '3'">
            批量删除</el-button>
          <el-button class="batch-btn" @click="showBatchDistribute"
            v-if="getVersionType() == 1 || getVersionType() == 4">批量设置提成</el-button>
          <el-button class="batch-btn" @click="showBatchCategory">批量设置分类</el-button>
          <el-button class="batch-btn" @click="showBatchStockWarn">批量设置库存预警</el-button>
          <el-button class="batch-btn" @click="showBatchGoodsTag">批量设置商品标签</el-button>
          <el-button class="batch-btn" @click="openBatchDeliveryTemplate">批量设置运费模板</el-button>
          <el-button class="batch-btn" @click="openBatchSetGoodsCustomsGoodsCode"
            v-if="enterpriseConfig.crossBorderBusinessFlag === 1">批量设置海关编码</el-button>
        </div>
      </div>

      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="goodsList" @selection-change="handleSelectionChange"
          v-loading="listLoading" element-loading-text="加载中" style="width: 100%" header-cell-class-name="default-header"
          row-class-name="default-row">
          <el-table-column width="50px" type="selection" fixed="left"></el-table-column>
          <el-table-column width="320px" label="商品" fixed="left">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p mar-r-30" @click="handleEdit(scope.row)">
                <label><img :src="scope.row.mainImage" class="user-avatar cursor-p"></label>
                <div class="font-14 pad-l-10 v-align-h height-65">
                  <div class="goods-title">
                    <div class="line-2">
                      <template v-if="scope.row.categoryName">
                        <el-tag size="mini" v-if="scope.row.skuFlag == 1" type="danger" effect="light">多</el-tag>
                      </template>
                      <template v-if="scope.row.crossBorderType === 2">
                        <el-tag size="mini" type="danger" effect="light">保</el-tag>
                      </template>
                      <template
                        v-if="enterpriseConfig.anchorSelectionAuthority == '1' && scope.row.selectionGoodsType == '1'">
                        <el-tag size="mini" class="anchor-tag" type="danger" effect="light">选</el-tag>
                      </template>
                      {{scope.row.title}}
                    </div>
                  </div>
                  <template v-if="scope.row.categoryName">
                    <span class="font-color-6 font-13">[{{scope.row.categoryName}}]</span>
                  </template>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="getVersionType() != 2 && getVersionType() != 3" width="180px" label="来源">
            <template slot-scope="scope">
              <span v-if="scope.row.goodsSource == 0">总部自营</span>
              <span v-if="scope.row.goodsSource == 1">{{scope.row.supplierName}}</span>
              <span v-if="scope.row.goodsSource == 2">淘宝联盟</span>
              <span v-if="scope.row.goodsSource == 3">供货联盟</span>
            </template>
          </el-table-column>
          <el-table-column width="140px" label="商品品牌" prop="brandName"></el-table-column>
          <el-table-column v-if="getVersionType() != 3" width="150px" label="供应价">
            <template slot-scope="scope">
              <template v-if="scope.row.goodsSource == 3">
                <span v-if="scope.row.supplyAlliancePrice">
                  <span> ￥{{scope.row.supplyAlliancePrice}} </span>
                  <span
                    v-if="scope.row.supplyAllianceMaxPrice !== null && scope.row.supplyAlliancePrice  !== scope.row.supplyAllianceMaxPrice">--￥{{scope.row.supplyAllianceMaxPrice}}
                  </span>
                </span>
                <span v-else>--</span>
              </template>
              <template v-else>
                <template v-if="scope.row.supplyPrice">
                  <span v-if="scope.row.supplyPrice">￥{{scope.row.supplyPrice}}</span>
                </template>
              </template>
            </template>
          </el-table-column>
          <el-table-column v-if="getVersionType() != 2 && getVersionType() != 3" width="140px" label="零售价">
            <template slot-scope="scope">
              ￥{{scope.row.sellPrice}}
            </template>
          </el-table-column>
          <el-table-column v-if="getVersionType() == 1" width="140px" label="分销佣金">
            <template slot-scope="scope">
              ￥{{scope.row.distributeIncome}}
            </template>
          </el-table-column>

          <el-table-column width="140px" label="库存">
            <template slot-scope="scope">

              <template v-if="scope.row.goodsSource === 3">
                <div>
                  <span>可用：</span>
                  <span>{{ scope.row.remainStock }}</span>
                </div>
                <div>
                  <span>占用：</span>
                  <span>{{ scope.row.stockInUse }}</span>
                </div>
              </template>

              <template v-else>
                <div>
                  <span>可用：</span>
                  <el-button type="text" @click="seeStockDetail(scope.row)">{{ scope.row.remainStock }}</el-button>
                </div>
                <div>
                  <span>占用：</span>
                  <el-button type="text" @click="seeStockDetail(scope.row)">{{ scope.row.stockInUse }}</el-button>
                </div>
              </template>

            </template>
          </el-table-column>
          <el-table-column width="140px" label="销量">
            <template slot-scope="scope">
              {{scope.row.salesNum}}{{scope.row.unit}}
            </template>
          </el-table-column>
          <el-table-column width="140px" label="序号" prop="sortNo"></el-table-column>
          <el-table-column width="140px" label="标签" :formatter="goodsTagFormatter" />
          <el-table-column width="140px" label="状态">
            <template slot-scope="scope">
              <template v-if="scope.row.stock == 0">
                已售空
              </template>
              <template v-else>
                <template v-if="scope.row.goodsStatusRemark">
                  <el-tooltip class="item" effect="dark" :content="scope.row.goodsStatusRemark" placement="top-start">
                    <span style="color: #2d8cf0">{{ dict.upDwonStatusFlag[scope.row.goodsStatus]}}</span>
                  </el-tooltip>
                </template>
                <template v-else>
                  {{ dict.upDwonStatusFlag[scope.row.goodsStatus]}}
                </template>
              </template>
            </template>
          </el-table-column>
          <el-table-column v-if="getVersionType() == 1" width="140px" label="销售库">
            <template slot-scope="scope">
              {{dict.distributionType[scope.row.distributionType]}}
            </template>
          </el-table-column>
          <el-table-column min-width="160px" label="操作" fixed="right" align="right">
            <template slot-scope="scope">
              <template v-if="scope.row.auditType === 0 && getVersionType() === '2'">
                <el-tag type="warning"> 审 核 中 </el-tag>
              </template>
              <template v-else>
                <template v-if="scope.row.supplyAllianceStatus === 3">
                  <el-button type="text" size="medium" @click="handleDelete(scope.row)">删除</el-button>
                </template>
                <template v-else>
                  <template v-if="scope.row.goodsStatus === 0 && scope.row.auditType !== 0">
                    <el-button type="text" size="medium" @click="handleUp(scope.row)">上架</el-button>
                  </template>
                  <template v-if="scope.row.goodsStatus === 1 && scope.row.auditType !== 0">
                    <el-button type="text" size="medium" @click="handleDown(scope.row)">下架</el-button>
                  </template>
                  <el-button type="text" size="medium" @click="handleEdit(scope.row)">编辑</el-button>
                  <el-popover placement="bottom" width="100" trigger="hover" popper-class="popover-class">
                    <el-button class="mar-l-10" type="text" size="medium" slot="reference">更多</el-button>
                    <div>
                      <el-button type="text" size="medium" @click="handleDelete(scope.row)">删除</el-button>
                    </div>
                    <div>
                      <el-button type="text" size="medium" @click="liveGoodsJoin(scope.row)"
                        v-if="scope.row.liveGoodsType === 0 && (getVersionType() == '1' || getVersionType() == '4') && scope.row.goodsStatus === 1">
                        加入直播库</el-button>
                    </div>
                    <div>
                      <el-button type="text" size="medium" @click="liveGoodsDelete(scope.row)"
                        v-if="scope.row.liveGoodsType === 1 && (getVersionType() == '1' || getVersionType() == '4')">
                        移出直播库
                      </el-button>
                    </div>
                    <!-- 开启主播选品 -->
                    <div v-if="enterpriseConfig.anchorSelectionAuthority == '1'">
                      <!-- 加入选品库 -->
                      <el-button type="text" size="medium" @click="openSelectionGoodsDialog(scope.row, '1')"
                        v-if="scope.row.selectionGoodsType == '0' && (getVersionType() == '1' || getVersionType() == '4') && scope.row.goodsStatus === 1">
                        加入选品库</el-button>
                      <!-- 移出选品库 -->
                      <el-button type="text" size="medium" @click="openSelectionGoodsDialog(scope.row, '0')"
                        v-if="scope.row.selectionGoodsType == '1' && (getVersionType() == '1' || getVersionType() == '4') && scope.row.goodsStatus === 1">
                        移出选品库</el-button>
                    </div>
                  </el-popover>
                </template>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <div>
      <el-dialog width="50%" v-el-drag-dialog title="批量设置提成" :visible.sync="batchDistributeVisible">
        <div>
          <el-form :model="batchDistribute">
            <el-form-item label-width="15%" v-if="getVersionType() == 1 || getVersionType() == 4">
              <el-radio-group v-model="batchDistribute.distributeType">
                <el-radio class="gray-active" :label="1" :class="1===batchDistribute.distributeType?'active':''">按比例设置
                </el-radio>
              </el-radio-group>
              <div class="gray-bar">
                <el-row>
                  <el-col :span="6" class="align-r pad-r-10">一级合伙人提成：</el-col>
                  <el-col :span="18">
                    <el-form-item style="background: #e4e4e4;" v-if="batchDistribute.distributeType == '1'" label=""
                      prop="distributeRatio">
                      <el-input v-model="batchDistribute.levelOnePartnerRatio" class="long-input"
                        @keyup.native="batchDistribute.levelOnePartnerRatio = checkInputNum(batchDistribute.levelOnePartnerRatio)">
                        <template slot="append">%</template>
                      </el-input>
                      <div class="tips">一级合伙人按商品分润获得的提成</div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" class="align-r pad-r-10">二级合伙人提成：</el-col>
                  <el-col :span="18">
                    <el-form-item style="background: #e4e4e4;" v-if="batchDistribute.distributeType == '1'" label=""
                      prop="distributeRatio">
                      <el-input v-model="batchDistribute.levelTwoPartnerRatio" class="long-input"
                        @keyup.native="batchDistribute.levelTwoPartnerRatio = checkInputNum(batchDistribute.levelTwoPartnerRatio)">
                        <template slot="append">%</template>
                      </el-input>
                      <div class="tips">二级合伙人按商品分润获得的提成</div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" class="align-r pad-r-10">招募员提成：</el-col>
                  <el-col :span="18">
                    <el-form-item style="background: #e4e4e4;" v-if="batchDistribute.distributeType == '1'" label=""
                      prop="distributeRatio">
                      <el-input v-model="batchDistribute.recruiterRatio" class="long-input"
                        @keyup.native="batchDistribute.recruiterRatio = checkInputNum(batchDistribute.recruiterRatio)">
                        <template slot="append">%</template>
                      </el-input>
                      <div class="tips">招募员按商品分润获得的提成</div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" class="align-r pad-r-10">微客佣金：</el-col>
                  <el-col :span="18">
                    <el-form-item style="background: #e4e4e4;" v-if="batchDistribute.distributeType == '1'" label=""
                      prop="distributeRatio">
                      <el-input v-model="batchDistribute.distributeRatio" class="long-input"
                        @keyup.native="batchDistribute.distributeRatio = checkInputNum(batchDistribute.distributeRatio)">
                        <template slot="append">%</template>
                      </el-input>
                      <div class="tips">开通萤火云店的微客分销商品后,获得的佣金</div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" class="align-r pad-r-10">顾客分销佣金：</el-col>
                  <el-col :span="18">
                    <el-form-item style="background: #e4e4e4;" v-if="batchDistribute.distributeType == '1'" label=""
                      prop="distributeRatio">
                      <el-input v-model="batchDistribute.shareMemberRatio" class="long-input"
                        @keyup.native="batchDistribute.shareMemberRatio = checkInputNum(batchDistribute.shareMemberRatio)">
                        <template slot="append">%</template>
                      </el-input>
                      <div class="tips">顾客帮店长分销商品后,获得的佣金（仅限一级）</div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-form-item>
          </el-form>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button @click="batchDistributeVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchDistribute">确定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="选择批发商品" :visible.sync="selectGoodsVisible" :close-on-press-escape="true" :center="true"
        width="850px">
        <div class="scroll-layer-box">
          <goods-select :goodsType="31" :onFinish="handleCopyFinish"></goods-select>
        </div>
      </el-dialog>

      <el-dialog title="" :visible.sync="liveGoodsVisible" :close-on-press-escape="true" :center="true" width="850px">
        <el-form :model="liveGoods" label-position="right" label-width="120px">
          <el-form-item label="商品封面">
            <el-upload list-type="picture-card" action="/api/common/uploadFiles"
              accept="image/jpeg,image/gif,image/png,image/bmp" name="files" :data="uploadParams"
              :show-file-list="false" :on-success="handleUploadSuccess" :before-upload="beforeUpload">
              <img v-if="liveGoods.goodsImgUrl" :src="liveGoods.goodsImgUrl" width="148px" height="148px"
                style="margin-left: -1px;margin-top: -1px;">
              <i v-else class="el-icon-plus"></i>
            </el-upload>
            <span>建议尺寸：200像素 * 200像素，图片大小不得超过50K。</span>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="liveGoods.title" class="width-per-70" placeholder="请输商品名称"></el-input><br />
            <span>商品名称必须为3-14个汉字（一个字等于两个英文字符或特殊字符）</span>
          </el-form-item>
          <el-form-item label="价格形式">
            <el-radio-group v-model="priceType">
              <el-radio v-if="liveGoods.skuFlag == 0" label="1" class="mar-b-10">
                <span class="width-100 display-inline">一口价</span>
                <span>价格</span>
                <el-input v-model="liveGoods.price" class="width-180" type="number">
                  <template slot="append">元</template>
                </el-input>
              </el-radio><br />
              <el-radio v-if="liveGoods.skuFlag == 1" label="2" class="mar-b-10">
                <span class="width-100 display-inline">价格区间</span>
                <span>价格</span>
                <el-input v-model="liveGoods.minPrice" class="width-180">
                  <template slot="append">元</template>
                </el-input>
                <span class="width-20 display-inline text-align-c">-</span>
                <el-input v-model="liveGoods.maxPrice" class="width-180" type="number">
                  <template slot="append">元</template>
                </el-input>
              </el-radio><br />
              <el-radio v-if="liveGoods.skuFlag == 0" label="3" class="mar-b-10">
                <span class="width-100 display-inline">显示折扣价</span>
                <span>原价</span>
                <el-input v-model="liveGoods.originalPrice" class="width-180">
                  <template slot="append">元</template>
                </el-input>
                <span class="width-20 display-inline text-align-c"></span>
                <span>现价</span>
                <el-input v-model="liveGoods.nowPrice" class="width-180" type="number">
                  <template slot="append">元</template>
                </el-input>
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="flex v-align-c">
          <span class="width-120"></span>
          <el-button type="primary" class="width-110" @click="addLiveGoods(0)">加入</el-button>
          <el-button type="primary" class="width-110" @click="addLiveGoods(1)">加入并审核</el-button>
          <el-button class="width-110" @click="liveGoodsVisible = false">取消</el-button>
        </div>
      </el-dialog>

      <!-- 选品库dialog -->
      <el-dialog :visible.sync="selectionGoodsVisible" title="加入/移出选品库" width="20%" :center="true">
        <el-header>
          <div>
            <label>操作：</label>
            <el-radio v-model="selectionGoodsForm.selectionGoodsType" label="1" name="1">加入选品库</el-radio>
            <el-radio v-model="selectionGoodsForm.selectionGoodsType" label="0" name="0">移出选品库</el-radio>
          </div>
          <div v-if="selectionGoodsForm.selectionGoodsType == 1">
            <label>平台：</label>
            <el-checkbox :checked="true" disabled>小程序直播</el-checkbox>
          </div>
          <div>
            <label>（抖音/快手等平台需到商品详情页设置）</label>
          </div>
        </el-header>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="doSaveSelectionGoodsType">保存</el-button>
          <el-button @click="closeSelectionGoodsDialog">取消</el-button>
        </div>
      </el-dialog>

      <!-- 批量设置分类的弹窗体 -->
      <el-dialog :visible.sync="batchCategoryDialogVisible" width="20%" v-el-drag-dialog :center="true">
        <el-form label-width="130px" style="width: 480px">
          <el-form-item label="零售商品分类:">
            <el-cascader v-model="categoryCopyIds" :props="{ checkStrictly: true }" change-on-select
              placeholder="选择商品分类" :options="categoryData" class="special-input" clearable></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleBatchCategory">保存</el-button>
          <el-button @click="batchCategoryDialogVisible = false">取消</el-button>
        </span>
      </el-dialog>

      <!-- 批量设置库存预警的弹窗体 -->
      <el-dialog :visible.sync="batchStockWarnVisible" width="20%" v-el-drag-dialog :center="true">
        <el-form label-width="100px" style="width: 480px;">
          <el-form-item label="预警数量:">
            <el-input style="width: 200px;" v-model="stockWarn" placeholder="请输入预警数量"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleBatchStockWarn">保存</el-button>
          <el-button @click="batchStockWarnVisible = false">取消</el-button>
        </span>
      </el-dialog>

      <!-- 外部编码配置dialog -->
      <el-dialog :visible.sync="externalCodeConfigVisible" title="商品外部编码批量生成规则" width="40%" center>
        <el-form ref="externalCodeConfigForm" :model="externalCodeConfigForm" label-width="130px" style="width: 480px">
          <el-form-item label="编码内容类型:">
            <el-select v-model="externalCodeConfigForm.contentType">
              <el-option v-for="(value,key) in externalCodeDict.contentType" :key="key" :label="value" :value="key">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容取用长度:"
            v-if="externalCodeConfigForm.contentType == 1 || externalCodeConfigForm.contentType == 2">
            <el-radio-group v-model="externalCodeConfigForm.selectType">
              <el-radio :label="1">
                <span style="color:black;margin-right:8px">头</span>
                <el-input v-model="externalCodeConfigForm.headLength" placeholder="请输入取用内容头部的长度"></el-input><span
                  style="color:black;margin-left:8px">个字符</span>
              </el-radio>
              <el-radio :label="2">
                <span style="color:black;margin-right:8px">尾</span>
                <el-input v-model="externalCodeConfigForm.tailLength" placeholder="请输入取用内容尾部的长度"></el-input><span
                  style="color:black;margin-left:8px">个字符</span>
              </el-radio>
              <el-radio :label="3">
                <span style="color:black">全部</span>
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="自定义内容:" v-if="externalCodeConfigForm.contentType == 3">
            <el-input v-model="externalCodeConfigForm.customizeContent" placeholder="请输入自定义编码内容"></el-input>
            <div style="color:gray">（自定义内容可以是字母、数字的组合，可以为空）</div>
          </el-form-item>
          <el-form-item label="随机内容长度:" v-if="externalCodeConfigForm.contentType == 4">
            <el-input v-model="externalCodeConfigForm.randomLength" placeholder="请输入随机内容长度"></el-input>
            <div style="color:gray">（系统随机生成内容为8~16个字母与数字组合）</div>
            <el-checkbox v-model="externalCodeConfigForm.autoGenerateCodeFlag">新增商品时，自动生成外部编码</el-checkbox>
          </el-form-item>
        </el-form>

        <div class="flex flex-center">
          <div v-if="externalCodeConfigForm.contentType == 1 || externalCodeConfigForm.contentType == 2">
            <div>当前编码格式：指定长度的商品货号或商品条码+自增编码</div>
            <div>（自增编码根据待生成SKU数量，自动匹配位数生成，例如001,002）</div>
          </div>
          <div v-if="externalCodeConfigForm.contentType == 3">
            <div>当前编码格式：自定义内容+自增编码</div>
            <div>（自增编码根据待生成SKU数量，自动匹配位数生成，例如001,002）</div>
          </div>
          <div v-if="externalCodeConfigForm.contentType == 4">当前编码格式：系统随机生成的指定长度的字母与数字组合</div>
        </div>
        <!-- footer -->
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveExternalCodeConfig()">保存</el-button>
          <!-- <el-button type="primary" @click="generateCodeAlertVisible = true">重新生成</el-button> -->
          <el-button @click="closeExternalCodeConfigDialog()">取消</el-button>
        </span>
        <!-- 内层dialog -->
        <el-dialog :visible.sync="generateCodeAlertVisible" width="22%" center append-to-body>
          <div>重新生成编码将覆盖所有商品现有的外部编码，有可能</div>
          <div>会导致与平台店铺编码不一致，且不可恢复，确定要重</div>
          <div>新生成？</div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="generateExtenalCode()">确定</el-button>
            <el-button @click="generateCodeAlertVisible = false">取消</el-button>
          </span>
        </el-dialog>
      </el-dialog>

      <!-- 商品仓库库存详情dialog -->
      <el-dialog title="商品仓库库存详情" :visible.sync="openStockDetail" :close-on-press-escape="true" :center="true"
        width="850px">
        <warehouse-goods-stock-detail :showFlag="openStockDetail" :goodsObj="selectGoodsObj"
          @callback="openStockDetail = false"></warehouse-goods-stock-detail>
      </el-dialog>

      <!-- 批量设置商品标签的弹窗 -->
      <el-dialog :visible.sync="batchGoodsTagDialogVisible" width="25%" v-el-drag-dialog :center="true">
        <el-form style="width: 520px">
          <el-form-item label="商品标签:">
            <el-select style="width: 250px;" multiple collapse-tags placeholder="请选择" v-model="selectedGoodsTag">
              <el-option v-for="item in goodsTagList" :key="item.goodsTagId" :label="item.goodsTagName"
                :value="item.goodsTagId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleBatchSaveGoodsTag">保存</el-button>
          <el-button @click="batchGoodsTagDialogVisible = false">取消</el-button>
        </span>
      </el-dialog>
      <!-- 商品库存详情dialog -->
      <el-dialog title="商品库存详情" :visible.sync="openStockDetail" :center="true" top="5vh" width="850px">
        <goods-stock-detail :showFlag="openStockDetail" :goodsObj="selectGoodsObj" @callback="openStockDetail = false">
        </goods-stock-detail>
      </el-dialog>

      <!-- 批量设置运费模板dialog -->
      <el-dialog title="批量设置运费模板" :visible.sync="batchDeliveryTemplateVisible" :center="true" width="500px">
        <batch-set-delivery-template :showFlag="batchDeliveryTemplateVisible" :goodsIds="selectionGoodsForm.goodsIds"
          @callback="doCallbackSetDeliveryTemplate"></batch-set-delivery-template>
      </el-dialog>
      <!-- 批量设置海关编码弹窗 -->
      <BatchSetCustomsGoodsCode ref="batchSetCustomsGoodsCodeRef"
        :onSuccess="handleBatchSetCustomsGoodsCodeSuccessCall">
      </BatchSetCustomsGoodsCode>

    </div>
  </div>
</template>

<script>
  import {
    getGoodsList,
    upGoods,
    downGoods,
    deleteGoods,
    handleBatchDown,
    handleBatchCategory,
    handleBatchStockWarn,
    handleDelete,
    handleBatchSetDistribute,
    listGoodsCategory,
    checkUploadTaoBaoZip,
    batchSelectionGoods
  } from '@/api/goods/goods'
  import {
    getLiveGoods,
    addLiveGoods,
    liveGoodsDelete,
    doApplyProjectGoodsPrice
  } from '@/api/goods/liveGoods'
  import {
    listBrand
  } from '@/api/user/enterpriseBrand'
  import {
    getDictByGroupName,
    getDictCommon
  } from '@/api/common/common'
  import {
    pageAuditGoods
  } from '@/api/goods/auditGoods'
  import {
    listSupplier
  } from '@/api/user/supplier'
  import {
    downloadFile
  } from '@/api/common/common'
  import {
    getToken
  } from '@/utils/auth'
  import {
    getByEnterpriseId
  } from '@/api/user/enterprise'
  import {
    getExternalCodeConfig,
    saveExternalCodeConfig,
    batchUpdateExternalCode
  } from '@/api/user/externalCodeConfig'
  import goodsSelect from '../components/goods-select'
  import goodsStockDetail from '@/views/goods/components/goods-stock-detail'
  import batchSetDeliveryTemplate from '@/views/goods/components/batch-set-delivery-template'
  import elDragDialog from '@/directive/el-dragDialog'
  import BatchSetCustomsGoodsCode from '@/views/goods/components/batch-set-customs-goods-code'
  import {
    getGoodsTagListByBusType,
    batchSaveGoodsTagDetail
  } from '@/api/goods/goodsTag'

  export default {
    components: {
      goodsSelect,
      goodsStockDetail,
      batchSetDeliveryTemplate,
      BatchSetCustomsGoodsCode
    },
    directives: {
      elDragDialog
    },
    data() {
      return {
        total: null,
        multipleSelection: [],
        listLoading: true,
        supplierList: [],
        listBrands: [],
        brandId: '',
        supplierType: '',
        searchListQuery: {
          enterpriseId: this.getEnterpriseId(),
          supplierId: '',
          currentPage: 1,
          size: 10,
          distributionType: null,
          supplierType: null,
          liveGoodsType: '',
          selectionGoodsType: '',
          title: '',
          comboType: '1',
          crossBorderType: ''
        },
        enterpriseConfig: {
          wholesaleAuthority: 0,
          crossBorderBusinessFlag: 0
        },
        supplierId: '',
        searchLabelType: '',
        textCol: 'title',
        searchKeyword: '',
        dict: {
          upDwonStatusFlag: {},
          crossBorderType: {}
        },
        isDict: false,
        pagingStatus: '0',
        categoryIds: [],
        categoryCopyIds: [],
        goodsList: [],
        comDict: {},
        // 选中商品对象
        selectGoodsObj: '',
        // 外部编码配置表数据字典
        externalCodeDict: {},
        // 商品的所有分类json
        categoryData: [],
        // 预警库存
        stockWarn: '',
        selectGoodsVisible: false,
        liveGoodsVisible: false,
        batchDistributeVisible: false,
        // 批量设置分类弹窗
        batchCategoryDialogVisible: false,
        // 批量设置库存预警弹窗
        batchStockWarnVisible: false,
        // 外部编码设置dialog
        externalCodeConfigVisible: false,
        generateCodeAlertVisible: false,
        // 批量设置运费模板dialog
        batchDeliveryTemplateVisible: false,
        // 外部编码表单
        externalCodeConfigForm: {
          enterpriseId: this.getEnterpriseId(),
          externalCodeConfigId: '',
          contentType: '1',
          selectType: 1,
          selectLength: 1,
          // head
          headLength: '',
          tailLength: '',
          customizeContent: '',
          randomLength: '',
          autoGenerateCodeFlag: true
        },
        // 商品分类
        goodscategoryIds: [],
        batchDistribute: {
          distributeType: 1,
          distributeRatio: '',
          distributeFee: '',
          shareMemberRatio: '',
          shareMemberFee: '',
          levelOnePartnerRatio: '',
          levelOnePartnerFee: '',
          levelTwoPartnerRatio: '',
          levelTwoPartnerFee: '',
          recruiterRatio: '',
          recruiterFee: ''
        },
        // 直播商品库
        liveGoods: {
          liveGoodsId: '',
          goodsImgUrl: '',
          priceType: '1',
          price: '',
          minPrice: '',
          maxPrice: '',
          originalPrice: '',
          nowPrice: '',
          auditStatus: '0',
          goodsId: '',
          enterpriseId: this.getEnterpriseId()
        },
        // 选品库
        selectionGoodsForm: {
          enterpriseId: this.getEnterpriseId(),
          goodsIds: [],
          selectionGoodsType: '1', // 加入选品库
          anchorPlatformShopType: '1' // 默认加入，不可更改
        },
        // 选品库dialog
        selectionGoodsVisible: false,
        goodsImgUrl: '',
        priceType: '1',
        allChecked: false,
        uploadParams: '',
        fileLoading: '',
        uploadCheckId: '',
        openStockDetail: false,
        goodsTagList: [],
        batchGoodsTagDialogVisible: false,
        selectedGoodsTag: []
      }
    },
    // 初始化页面
    created() {
      this.uploadParams = {
        accessToken: getToken(),
        enterpriseId: this.getEnterpriseId(),
        goodsType: 30
      }
      const queryParams = this.getCurrentPage().query
      if (queryParams && queryParams.supplierId) {
        this.supplierId = queryParams.supplierId
      }
      if (queryParams && queryParams.currentPage) {
        this.searchListQuery.currentPage = queryParams.currentPage * 1
      }
      this.listBrand()
      this.initEnterpriseConfig()
      this.listSupplier()
      this.initDict()
      this.listGoodsCategory()
      this.initGoodsList()
      this.initDictCommon()
      this.getGoodsTagList()
    },
    methods: {
      listBrand() {
        listBrand(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.listBrands = response.data
        })
      },
      initEnterpriseConfig() {
        getByEnterpriseId(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.enterpriseConfig = response.data
        })
      },
      initDictCommon() {
        getDictCommon().then(response => {
          this.comDict = response.data
        })
      },
      listSupplier() {
        listSupplier({
          enterpriseId: this.getEnterpriseId()
        }).then(response => {
          if (response.isError) return
          this.supplierList = response.data
        })
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initGoodsList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initGoodsList()
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.goodsList.length) {
          this.goodsList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
            // this.allChecked = true
          })
        } else {
          this.$refs.multipleTable.clearSelection()
          // this.allChecked = false
        }
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.goodsList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      initDict() {
        getDictByGroupName('ProjectGoodsDTO').then(response => {
          this.dict = response.data
        })
        getDictByGroupName('ExternalCodeConfigDTO').then(response => {
          this.externalCodeDict = response.data
        })
      },
      setSearchListQuery() {
        this.searchListQuery = {
          enterpriseId: this.getEnterpriseId(),
          supplierId: '',
          currentPage: this.searchListQuery.currentPage,
          size: this.searchListQuery.size,
          distributionType: this.searchListQuery.distributionType,
          supplierType: null,
          liveGoodsType: this.searchListQuery.liveGoodsType,
          selectionGoodsType: this.searchListQuery.selectionGoodsType,
          comboType: 1,
          crossBorderType: this.searchListQuery.crossBorderType
        }
        this.searchListQuery['supplierId'] = this.supplierId
        if (this.searchLabelType) {
          this.searchListQuery['labelType'] = this.searchLabelType
        }
        this.searchListQuery[this.textCol] = this.searchKeyword
        this.searchListQuery['goodsSource'] = ''
        this.searchListQuery['supplierType'] = ''
        this.searchListQuery['supplierId'] = ''
        if (this.supplierType === '') {
          console.log('')
        } else if (this.supplierType === '1') {
          this.searchListQuery['goodsSource'] = '0'
        } else if (this.supplierType === '2') {
          this.searchListQuery['goodsSource'] = '2'
        } else if (this.supplierType === '3') {
          this.searchListQuery['goodsSource'] = '3'
        } else {
          this.searchListQuery['goodsSource'] = '1'
          this.searchListQuery['supplierId'] = this.supplierType
          this.searchListQuery['supplierType'] = 2
        }
        this.searchListQuery['oneCategoryId'] = ''
        this.searchListQuery['twoCategoryId'] = ''
        this.searchListQuery['threeCategoryId'] = ''
        const categoryIds = this.categoryIds
        if (categoryIds.length === 1) {
          this.searchListQuery['oneCategoryId'] = categoryIds[0]
        }
        if (categoryIds.length === 2) {
          this.searchListQuery['twoCategoryId'] = categoryIds[1]
        }
        if (categoryIds.length === 3) {
          this.searchListQuery['threeCategoryId'] = categoryIds[2]
        }
        this.searchListQuery['pagingStatus'] = this.pagingStatus
      },
      initGoodsList() {
        this.setSearchListQuery()
        this.listLoading = true
        if (this.getVersionType() === '2') {
          // 供应商版
          pageAuditGoods(this.searchListQuery).then(response => {
            this.total = response.data.total
            this.goodsList = response.data.records
            if (!this.isDict) {
              this.dict = response.data.dict
              this.isDict = true
            }
            this.listLoading = false
          })
        } else {
          const goodsTypes = [30, 32]
          this.searchListQuery.goodsTypes = goodsTypes.join(',')
          this.searchListQuery.brandId = this.brandId
          getGoodsList(this.searchListQuery).then(response => {
            this.total = response.total
            this.goodsList = response.records
            if (!this.isDict) {
              this.dict = response.dict
              this.isDict = true
            }
            this.listLoading = false
          })
        }
      },
      // 获取类目
      listGoodsCategory() {
        const enterpriseId = this.getEnterpriseId()
        listGoodsCategory(enterpriseId).then(response => {
          this.categoryData = response.data
        })
      },
      handleCopyWholesale() {
        this.selectGoodsVisible = true
      },
      handleCopyFinish() {
        this.selectGoodsVisible = false
        this.initGoodsList()
      },
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.initGoodsList()
      },
      resetSearch() {
        this.searchKeyword = ''
        this.searchLabelType = ''
        this.supplierType = ''
        this.categoryIds = []
        this.brandId = ''
        this.searchListQuery = {
          enterpriseId: this.getEnterpriseId(),
          supplierId: '',
          currentPage: 1,
          size: 10,
          distributionType: null,
          goodsSource: '',
          supplierType: '',
          liveGoodsType: '',
          selectionGoodsType: '',
          title: '',
          crossBorderType: ''
        }
        this.initGoodsList()
      },
      // 商品状态
      goodsStatusClick() {
        this.handleSearch()
      },
      // 上架
      handleUp(row) {
        if (!row.sellPrice) {
          this.$message({
            type: 'warning',
            message: '零售价为空无法上架'
          })
          return
        }
        if (row.supplyAllianceUpdateType !== 0) {
          this.$confirm('商品信息已更新，是否确认上架？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            upGoods(row.goodsId, 30).then(response => {
              if (response.isError) return
              this.$message({
                message: '上架成功',
                type: 'success'
              })
              this.initGoodsList()
            })
          }).catch(() => {})
        } else {
          upGoods(row.goodsId, 30).then(response => {
            if (response.isError) return
            this.$message({
              message: '上架成功',
              type: 'success'
            })
            this.initGoodsList()
          })
        }
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'

        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
        }
        this.fileLoading = true
        return (isJPG || isBMP || isGIF || isPNG)
      },
      handleUploadSuccess(res, file) {
        if (res.code === 101) {
          this.liveGoods.goodsImgUrl = res.data[0]
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          return false
        }
      },
      // 打开批量设置运费模板
      openBatchDeliveryTemplate() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            type: 'error',
            message: '请勾选商品'
          })
          return
        }
        this.selectionGoodsForm.goodsIds = this.multipleSelection.map(item => item.goodsId)
        this.batchDeliveryTemplateVisible = true
      },
      // 批量设置运费模板回调
      doCallbackSetDeliveryTemplate(callbackFlag) {
        if (callbackFlag) {
          this.initGoodsList()
        }
        this.batchDeliveryTemplateVisible = false
      },
      // 上传淘宝商品压缩包
      beforeZipUpload(file) {
        if (file.size / 1024 / 1024 > 50) {
          this.$message.error('上传文件大小不能超过50MB!')
        }
        this.fileLoading = true
        return true
      },
      handleUploadZipSuccess(res, file) {
        if (res.code === 101) {
          this.uploadCheckId = res.data
          this.checkUploadTaoBaoZip()
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          return false
        }
      },
      checkUploadTaoBaoZip() {
        checkUploadTaoBaoZip(this.uploadCheckId).then(response => {
          if (response.isError) return
          if (response.data * 1 === 1) {
            this.fileLoading = false
            this.$message.success('上传成功')
            this.initGoodsList()
          } else {
            setTimeout(() => {
              this.checkUploadTaoBaoZip()
            }, 3000)
          }
        })
      },
      // 下架
      handleDown(row) {
        const goodsId = row.goodsId
        downGoods(goodsId, 30)
          .then(response => {
            if (response.isError) return
            this.$message({
              message: '下架成功',
              type: 'success'
            })
            this.initGoodsList()
          })
      },
      handleCreate() {
        const routeData = this.$router.resolve({
          path: '/goods/edit/index',
          query: {
            fromListPage: '30'
          }
        })
        const newWindow = window.open(routeData.href, 'newRetailGoods')
        newWindow.onload = () => (newWindow.document.title = '新建零售商品')
      },
      // 编辑
      handleEdit(row) {
        if (row.supplyAllianceStatus === 1 && row.goodsSource === 0) {
          this.$message({
            type: 'error',
            message: '商品已在供货联盟上架，编辑前请先下架商品!'
          })
          return
        }
        const routeData = this.$router.resolve({
          path: '/goods/edit/index',
          query: {
            goodsId: row.goodsId,
            fromListPage: '30'
          }
        })
        const newWindow = window.open(routeData.href, row.goodsId)
        newWindow.onload = () => (newWindow.document.title = row.title)
      },
      // 删除
      handleDelete(row) {
        this.$confirm('此操作将删除该商品，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const goodsId = row.goodsId
          deleteGoods(goodsId, 30).then(response => {
            if (response.isError) return
            this.initGoodsList()
          })
        })
      },
      liveGoodsJoin(row) {
        this.liveGoods = {}
        getLiveGoods(row.goodsId).then(response => {
          if (response.isError) return
          this.liveGoods = response.data
          this.priceType = response.data.priceType ? response.data.priceType.toString() : '1'
          this.liveGoodsVisible = true
        })
      },
      liveGoodsDelete(row) {
        if (row.auditStatus === 0 || row.auditStatus === 2 || row.auditStatus === 3) {
          let remark = '确定要将商品移出直播商品库？'
          if (row.auditStatus === 2) {
            remark = '此商品将从所有直播间中同时删除，且不可恢复，确定要移出吗？'
          }
          this.$confirm(remark, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            liveGoodsDelete(row.liveGoodsId).then(response => {
              if (response.isError) return
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.initGoodsList()
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
        }
        if (row.auditStatus === 1) {
          this.$alert('商品库审核中的商品不允许移出。', '', {
            confirmButtonText: '关闭'
          })
        }
      },
      addLiveGoods(auditStatus) {
        if (this.priceType === '1' && (!this.liveGoods.price || this.liveGoods.price <= 0)) {
          this.$message.error('一口价不能为空且要大于0')
          return
        }
        if (this.priceType === '2' && (!this.liveGoods.maxPrice || this.liveGoods.maxPrice <= 0)) {
          this.$message.error('最低价不能为空且要大于0')
          return
        }
        if (this.priceType === '2' && (!this.liveGoods.minPrice || this.liveGoods.minPrice <= 0)) {
          this.$message.error('最高价不能为空且要大于0')
          return
        }
        if (this.priceType === '3' && (!this.liveGoods.originalPrice || this.liveGoods.originalPrice <= 0)) {
          this.$message.error('原价不能为空且要大于0')
          return
        }
        if (this.priceType === '3' && (!this.liveGoods.nowPrice || this.liveGoods.nowPrice <= 0)) {
          this.$message.error('现价不能为空且要大于0')
          return
        }
        this.liveGoods.priceType = this.priceType
        this.liveGoods.enterpriseId = this.getEnterpriseId()
        this.liveGoods.auditStatus = auditStatus
        doApplyProjectGoodsPrice(this.liveGoods).then(response => {
          if (response.isError) return
          if (response.data === true) {
            this.saveGoods()
          } else {
            this.$confirm('您设置的价格与商品当前价格不一致，可能导致直播间显示价格与商品详情页显示价格不一致，确认保存？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.saveGoods()
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              })
            })
          }
        })
      },
      saveGoods() {
        addLiveGoods(this.liveGoods).then(response => {
          if (response.isError) return
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.liveGoodsVisible = false
          this.initGoodsList()
        })
      },
      // 变更商品选品库选择状态
      doSaveSelectionGoodsType() {
        batchSelectionGoods(this.selectionGoodsForm).then(response => {
          if (response.isError) return
          this.$message({
            type: 'success',
            message: '加入/移出选品库成功'
          })
          this.initGoodsList()
          this.selectionGoodsVisible = false
        })
      },
      // 打开选品库dialog
      openSelectionGoodsDialog(row, selectionGoodsType) {
        if (selectionGoodsType === '1') {
          if (row.crossBorderType === 2) {
            this.msgError('所选商品中不能包含跨境商品，请重新选择。')
            return
          }
        }
        this.selectionGoodsForm.goodsIds = []
        this.selectionGoodsForm.selectionGoodsType = selectionGoodsType
        this.selectionGoodsForm.goodsIds.push(row.goodsId)
        this.selectionGoodsVisible = true
      },
      // 打开 批量加入/移出选品库dialog
      openBatchSelectionGoodsDialog() {
        // 当未勾选数据时，将当前所有已上架状态的商品加入选品库中
        // 已勾选数据，则改变对应的商品
        this.selectionGoodsForm.goodsIds = []
        const selections = this.multipleSelection
        if (selections !== undefined && selections.length > 0) {
          for (var i = 0; i < selections.length; i++) {
            const goods = selections[i]
            if (goods.crossBorderType === 2) {
              this.msgError('所选商品中不能包含跨境商品，请重新选择。')
              return
            }
            this.selectionGoodsForm.goodsIds.push(goods.goodsId)
          }
        }
        this.selectionGoodsVisible = true
      },
      // 关闭选品库dialog
      closeSelectionGoodsDialog() {
        this.selectionGoodsVisible = false
      },
      // 批量下架
      handleBatchDown() {
        const selections = this.multipleSelection
        if (selections.length === 0) {
          this.$message({
            type: 'error',
            message: '请勾选商品!'
          })
          return
        }
        const array = []
        selections.forEach(e => {
          array.push(e.goodsId)
        })
        const params = {
          goodsIds: array,
          goodsType: 30
        }
        handleBatchDown(params).then(response => {
          if (response.isError) return
          this.$message({
            message: '下架成功',
            type: 'success'
          })
          this.initGoodsList()
        })
      },
      // 批量删除
      handleBatchDelete() {
        const selections = this.multipleSelection
        if (selections.length === 0) {
          this.$message({
            type: 'error',
            message: '请勾选商品!'
          })
          return
        }
        this.$confirm('此操作将批量删除商品，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const array = []
          selections.forEach(e => {
            array.push(e.goodsId)
          })
          const params = {
            goodsIds: array,
            goodsType: 30
          }
          handleDelete(params).then(response => {
            if (response.isError) return
            this.$message({
              message: '成功删除',
              type: 'success'
            })
            this.initGoodsList()
          })
        })
      },
      // 批量设置提成
      showBatchDistribute() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            type: 'error',
            message: '请勾选商品!'
          })
          return
        }
        this.batchDistributeVisible = true
      },
      handleBatchDistribute() {
        if (!this.batchDistribute.distributeRatio && !this.batchDistribute.shareMemberRatio && !this.batchDistribute
          .levelOnePartnerRatio && !this.batchDistribute.levelTwoPartnerRatio && !this.batchDistribute.recruiterRatio) {
          // 产品说没填数据，直接提示成功
          this.$message({
            message: '批量更新成功',
            type: 'success'
          })
          return
        }
        if (!this.checkDistributeRatio(this.batchDistribute.distributeRatio)) {
          return
        }
        if (!this.checkDistributeRatio(this.batchDistribute.shareMemberRatio)) {
          return
        }
        if (!this.checkDistributeRatio(this.batchDistribute.levelOnePartnerRatio)) {
          return
        }
        if (!this.checkDistributeRatio(this.batchDistribute.levelTwoPartnerRatio)) {
          return
        }
        if (!this.checkDistributeRatio(this.batchDistribute.recruiterRatio)) {
          return
        }
        this.batchDistributeVisible = false
        const goodsIds = this.multipleSelection.map(e => e.goodsId)
        this.batchDistribute.goodsIds = goodsIds
        handleBatchSetDistribute(this.batchDistribute).then(response => {
          if (response.isError) return
          this.$message({
            message: '批量更新成功',
            type: 'success'
          })
          this.batchDistributeVisible = false
          this.initGoodsList()
        })
      },
      // 批量设置分类弹窗校验
      showBatchCategory() {
        const selections = this.multipleSelection
        if (selections.length === 0) {
          this.$message({
            type: 'error',
            message: '请勾选商品!'
          })
          return
        }
        this.batchCategoryDialogVisible = true
      },
      // 批量设置分类
      handleBatchCategory() {
        const selections = this.multipleSelection
        if (selections.length === 0) {
          this.$message({
            type: 'error',
            message: '请勾选商品!'
          })
          return
        }
        const array = []
        selections.forEach(e => {
          array.push(e.goodsId)
        })
        const params = {
          goodsIds: array,
          goodsType: 30,
          oneCategoryId: this.categoryCopyIds[0],
          twoCategoryId: this.categoryCopyIds[1],
          threeCategoryId: this.categoryCopyIds[2]
        }
        handleBatchCategory(params).then(response => {
          if (response.isError) return
          this.$message({
            message: '分类设置成功',
            type: 'success'
          })
          this.batchCategoryDialogVisible = false
          this.initGoodsList()
        })
      },
      // 批量设置库存预警
      showBatchStockWarn() {
        const selections = this.multipleSelection
        if (selections.length === 0) {
          this.$message({
            type: 'error',
            message: '请勾选商品!'
          })
          return
        }
        this.batchStockWarnVisible = true
      },
      // 批量设置库存预警
      handleBatchStockWarn() {
        if (!this.stockWarn) {
          this.$message({
            type: 'error',
            message: '请输入预警数量!'
          })
          return
        }
        const params = {
          goodsIds: this.multipleSelection.map(item => item.goodsId).join(','),
          stockWarn: this.stockWarn
        }
        handleBatchStockWarn(params).then(response => {
          if (response.isError) return
          this.$message({
            message: '设置成功',
            type: 'success'
          })
          this.batchStockWarnVisible = false
          this.initGoodsList()
        })
      },
      // 检查比例
      checkDistributeRatio(ratio) {
        if (ratio * 1 > 100) {
          this.$message({
            type: 'error',
            message: '比例不能超过100!'
          })
          return false
        }
        return true
      },
      // 导出
      handleExport() {
        const params = {
          enterpriseId: this.getEnterpriseId(),
          goodsTypes: '30, 32'
        }
        if (this.multipleSelection.length > 0) {
          params.goodsIds = this.multipleSelection.map(e => e.goodsId).join(',')
        } else {
          this.setSearchListQuery()
          Object.assign(params, this.searchListQuery)
        }
        downloadFile('/goods/projectGoods/exportGoods', params, '商品列表.xlsx')
      },
      // 获取企业外部编码
      getExternalCodeConfig() {
        const enterpriseId = this.getEnterpriseId()
        getExternalCodeConfig(enterpriseId).then(response => {
          if (response.isError) return
          if (response.data !== undefined) {
            this.externalCodeConfigForm = response.data
            // contentType 转换成字符串
            this.externalCodeConfigForm.contentType = this.externalCodeConfigForm.contentType.toString()
            // 商品货号和商品条码
            if (this.externalCodeConfigForm.contentType === '1' || this.externalCodeConfigForm.contentType ===
              '2') {
              if (this.externalCodeConfigForm.selectType === 1) {
                // 头部
                this.externalCodeConfigForm.headLength = this.externalCodeConfigForm.selectLength
              }
              if (this.externalCodeConfigForm.selectType === 2) {
                // 尾部
                this.externalCodeConfigForm.tailLength = this.externalCodeConfigForm.selectLength
              }
            }
          }
        })
      },
      // 保存外部编码设置
      saveExternalCodeConfig() {
        // 商品货号和商品条码
        if (this.externalCodeConfigForm.contentType === '1' || this.externalCodeConfigForm.contentType === '2') {
          if (this.externalCodeConfigForm.selectType === 1) {
            // 头部
            if (this.externalCodeConfigForm.headLength) {
              this.externalCodeConfigForm.selectLength = this.externalCodeConfigForm.headLength
            } else {
              this.$message({
                type: 'error',
                message: '请输入取用内容头部的长度'
              })
              return
            }
          }
          if (this.externalCodeConfigForm.selectType === 2) {
            // 尾部
            if (this.externalCodeConfigForm.tailLength) {
              this.externalCodeConfigForm.selectLength = this.externalCodeConfigForm.tailLength
            } else {
              this.$message({
                type: 'error',
                message: '请输入取用内容尾部的长度'
              })
              return
            }
          }
        }
        this.handleExternalCodeParam()
        saveExternalCodeConfig(this.externalCodeConfigForm).then(response => {
          if (response.isError) return
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          this.initGoodsList()
          this.externalCodeConfigVisible = false
        })
      },
      // 生成外部编码
      generateExtenalCode() {
        // 先保存
        // 商品货号和商品条码
        if (this.externalCodeConfigForm.contentType === '1' || this.externalCodeConfigForm.contentType === '2') {
          if (this.externalCodeConfigForm.selectType === 1) {
            // 头部
            if (this.externalCodeConfigForm.headLength) {
              this.externalCodeConfigForm.selectLength = this.externalCodeConfigForm.headLength
            } else {
              this.$message({
                type: 'error',
                message: '请输入取用内容头部的长度'
              })
              return
            }
          }
          if (this.externalCodeConfigForm.selectType === 2) {
            // 尾部
            if (this.externalCodeConfigForm.tailLength) {
              this.externalCodeConfigForm.selectLength = this.externalCodeConfigForm.tailLength
            } else {
              this.$message({
                type: 'error',
                message: '请输入取用内容尾部的长度'
              })
              return
            }
          }
        }
        this.handleExternalCodeParam()
        saveExternalCodeConfig(this.externalCodeConfigForm).then(response => {
          if (response.isError) return
          // 重新生成外部编码接口
          batchUpdateExternalCode(this.getEnterpriseId()).then(response => {
            if (response.isError) return
            this.$message({
              type: 'success',
              message: '商品外部编码更新成功'
            })
            this.generateCodeAlertVisible = false
          })
        })
      },
      // 字段校验处理
      handleExternalCodeParam() {
        // 随机
        if (this.externalCodeConfigForm.contentType === '4') {
          if (this.externalCodeConfigForm.autoGenerateCodeFlag) {
            this.externalCodeConfigForm.autoGenerateCodeFlag = 1
          } else {
            this.externalCodeConfigForm.autoGenerateCodeFlag = 0
          }
        }
      },
      // 打开外部编码配置dialog
      openExternalCodeConfigDialog() {
        // 获取企业外部编码配置信息
        this.externalCodeConfigForm.contentType = this.externalCodeConfigForm.contentType.toString()
        this.getExternalCodeConfig()
        this.externalCodeConfigVisible = true
      },
      // 关闭外部编码配置dialog
      closeExternalCodeConfigDialog() {
        this.externalCodeConfigVisible = false
      },
      // 查看库存明细
      seeStockDetail(row) {
        this.selectGoodsObj = row
        this.openStockDetail = true
      },
      // 打开批量导入商品视图
      openImportGoods() {
        const routeData = this.$router.resolve({
          path: '/goods/import-goods/index',
          query: {}
        })
        window.open(routeData.href, '_blank')
      },
      showBatchGoodsTag() {
        const selections = this.multipleSelection
        if (selections.length === 0) {
          this.msgError('请勾选商品')
          return
        }
        this.batchGoodsTagDialogVisible = true
      },
      handleBatchSaveGoodsTag() {
        const selections = this.multipleSelection
        if (selections.length === 0) {
          this.msgError('请勾选商品')
          return
        }
        if (this.selectedGoodsTag.length === 0) {
          this.msgError('请选择标签')
          return
        }
        const goodsIdList = []
        selections.forEach(e => {
          goodsIdList.push(e.goodsId)
        })
        const data = {}
        data.goodsIdList = goodsIdList
        data.goodsTagIdList = this.selectedGoodsTag
        data.goodsTagBusType = 1
        batchSaveGoodsTagDetail(data).then(response => {
          if (response.isError) return
          this.msgSuccess('设置成功')
          this.batchGoodsTagDialogVisible = false
          this.initGoodsList()
          this.selectedGoodsTag = []
        })
      },
      getGoodsTagList() {
        getGoodsTagListByBusType(1, this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.goodsTagList = response.data
        })
      },
      goodsTagFormatter(row) {
        if (row.goodsTagList !== null && row.goodsTagList !== undefined && row.goodsTagList.length > 0) {
          let tagTip = ''
          row.goodsTagList.forEach(goodsTag => {
            if (goodsTag.goodsTagBusType === 1) {
              tagTip = tagTip + goodsTag.goodsTagName + ' | '
            }
          })
          if (tagTip !== '') {
            tagTip = tagTip.substring(0, tagTip.length - 2)
          }
          return tagTip
        }
        return '-'
      },
      openBatchSetGoodsCustomsGoodsCode() {
        this.setSearchListQuery()
        this.searchListQuery.goodsTypes = '30'
        this.searchListQuery.brandId = this.brandId
        this.$refs.batchSetCustomsGoodsCodeRef.open(this.searchListQuery)
      },
      handleBatchSetCustomsGoodsCodeSuccessCall() {
        this.initGoodsList()
      }
    }
  }
</script>
<style lang="less" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .btn-search {
    height: 60px;
    display: flex;
    align-items: center;
  }

  .v-align-h {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: space-between;
  }

  .user-avatar {
    width: 65px;
    height: 65px;
    display: block;
    padding: 1px;
  }

  .goods-title {
    color: #155bd4;
    line-height: 1.2;
  }

  .gray-bar {
    background: #e4e4e4;
    padding: 20px;
    margin-bottom: 20px;
    width: 80%;
  }

  .tips {
    color: gray;
    font-size: 12px;
    line-height: 1.2;
    padding-top: 5px;
  }

  .special-input {
    /deep/ .el-input {
      width: 150px;
    }
  }

  // 2行文字展示
  .line-2 {
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-word;
  }

  .anchor-tag {
    color: #008425;
    background-color: #E3FFEB;
    border-color: #0084251a;
  }
</style>
